import { Component, OnInit, Input } from '@angular/core';
import { Base64ToGallery } from '@ionic-native/base64-to-gallery/ngx';
import { ExportAsService, ExportAsConfig } from 'ngx-export-as';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { ShareService } from 'src/app/shared/service/share.service';
import QRCode from 'qrcode';
import { HttpService } from 'src/app/shared/service/http.service';
import { Platform } from '@ionic/angular';

declare var $: any;
@Component({
  selector: 'app-poster-sharing',
  templateUrl: './poster-sharing.component.html',
  styleUrls: ['./poster-sharing.component.scss'],
})
export class PosterSharingComponent implements OnInit {
  qrCodeUrl: any;
  exportAsConfig: ExportAsConfig = {
    type: 'png', // the type you want to
    options: {
      useCORS: true,
      scale: 4
    },
    elementId: 'html2canvas' // the id of html/table element
  };
  baseDataContent: any;
  appTypeCustom: any;
  uuid = 'psuuid';
  isShowCopyBtnImg = true;
  constructor(
    private exportAsService: ExportAsService,
    private base64ToGallery: Base64ToGallery,
    private gloadService: AppGlobalService,
    private platform: Platform,
    private http: HttpService,
    private shareService: ShareService
  ) { }

  @Input() tagData: any;
  ngOnInit() {
    try {
      if (this.tagData.data.info.scale > 1) {
        this.exportAsConfig.options.scale = this.tagData.data.info.scale;
      }
      this.uuid += new Date().getTime();
      const bodyStyles = window.getComputedStyle(document.body);
      this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
      const en = window.navigator.userAgent.toLowerCase();
      const isWeixin = en.indexOf('micromessenger') !== -1;
      let dataUrl = this.tagData.data.info.code;
      if (!isWeixin) {
        dataUrl = this.tagData.data.info.code + '&posterSharing=true';
      }
      const opts = {
        errorCorrectionLevel: 'L',
        type: 'image/webp',
        quality: 1,
        // width: 200,
        // height: 200,
        // margin: 8,
        maskPattern: 7,
      };
      const tempUrl = decodeURI(dataUrl);

      QRCode.toDataURL(tempUrl, opts)
        .then(url => {
          this.qrCodeUrl = url;
          document.getElementById('img_detail_qr').setAttribute('src', this.qrCodeUrl);
        }).catch(err => {
          console.log('QRCode.toDataURL' + err);
        });
    } catch (error) {
    }
  }
  savePic(isFromDouyin?, title?, description?, webpageUrl?, type?) {
    this.isShowCopyBtnImg = false; //
    setTimeout(() => {
      const btnId = type + this.uuid;
      this.setBtnDisabled(btnId);
      const that = this;
      const element = document.getElementById('html2canvas');

      let sharebtn = $("#share-height").offset().top;
      sharebtn = sharebtn - 48;
      console.log('share-height:' + sharebtn);
      document.getElementById('posterSharingIdForSavePic').style.height = sharebtn + 'px';
      const targetElement = document.getElementById('posterSharingIdForSavePic').cloneNode(true);
      // crossOrigin="anonymous"
      element.appendChild(targetElement);
      // const dom = element.querySelector('#posterSharingIdForSavePic').querySelectorAll('img');
      this.exportAsService.get(this.exportAsConfig).subscribe(content => {
        that.download(content, isFromDouyin, title, description, webpageUrl, type);
        element.removeChild(targetElement);
      });
    }, 500);
  }

  download(dataUrl, isFromDouyin?, title?, description?, webpageUrl?, type?) {
    if (localStorage.getItem('client') === 'BROWSER') {
      const myBlob = this.dataURLtoBlob(dataUrl);
      const myUrl = URL.createObjectURL(myBlob);
      this.downloadFile(myUrl, 'deatil');
      this.setBtnEnable(type + this.uuid);
      this.isShowCopyBtnImg = true;

    } else {
      this.gloadService.showToast('正在保存中...', 1500, 'top');
      this.base64ToGallery.base64ToGallery(dataUrl, { prefix: isFromDouyin&&isFromDouyin==='true' ? 'isFromDouyin' : '_img', mediaScanner: true }).then(
        (res) => {
          this.setBtnEnable(type + this.uuid);
          if (isFromDouyin) {
            const filePath = "file://" + res;
            const fileArray = [filePath];
            this.shareService.shareDouyin(title, description, fileArray, webpageUrl);
          } else if (type && type === 'wechat') {
            if (localStorage.getItem('platform') === 'android') {
              this.shareService.shareWeiXinImage(title, description, dataUrl, dataUrl);
            } else {
              this.shareService.shareWeiXinImage(title, description, res, res);
            }

          } else if (type && type === 'qq') {
            if (localStorage.getItem('platform') === 'android') {
              this.shareService.shareQQImage(title, description, dataUrl, dataUrl);
            } else {
              this.shareService.shareQQImage(title, description, res, res);
            }

          } else {
            this.gloadService.showToast('保存成功!', 1500, 'top');
          }
          this.isShowCopyBtnImg = true;
          // if (document.getElementById('copySmallBtn' + this.uuid) !== null) {
          //   document.getElementById('copySmallBtn' + this.uuid).style.display = 'initial';
          // }
        },
        err => {
          console.log('Error saving image to gallery ', err);
          this.gloadService.showToast('保存出错了', 1500, 'top');
        }
      );
      // }
    }
  }
  uploadForUrl(blobFile, callBackFunction) {
    const imgBlob = blobFile;
    const formData = new FormData();
    formData.append('file', imgBlob, new Date().getTime + '.jpg');
    this.http.img_post('file/simpleUpload', formData, res => {
      callBackFunction(res.url);
    }, (error) => {
      callBackFunction('https://zeno-img.oss-cn-shenzhen.aliyuncs.com/file_1619507155797e2b8b0d2e4448992a630dd525faa6cbf.png');
    });
  }
  dataURLtoBlob(dataurl) {
    const arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  }

  downloadFile(url, name) {
    const a = document.createElement("a");
    a.setAttribute("href", url);
    a.setAttribute("download", name);
    a.setAttribute("target", "_blank");
    const clickEvent = document.createEvent("MouseEvents");
    clickEvent.initEvent("click", true, true);
    a.dispatchEvent(clickEvent);
  }
  shareWechat(isDouyin, title, content, imgUrl, webpageUrl) {
    this.savePic(isDouyin, title, content, webpageUrl, 'wechat');
  }
  shareQQ(isDouyin, title, content, imgUrl, webpageUrl) {
    this.savePic(isDouyin, title, content, webpageUrl, 'qq');
  }

  shareEnterpriseWechat(shareType, title, content, imageUrl, webpageUrl) {
    this.shareService.shareEnterpriseWechat(title, content, imageUrl, webpageUrl, shareType);
  }
  public getBase64Image(imgUrl): Promise<string> {
    try {
      return new Promise<string>(resolve => {
        const img = new Image();
        img.src = imgUrl;
        img.setAttribute('crossOrigin', 'anonymous');
        img.onload = (() => {
          const canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0);
          const dataURL = canvas.toDataURL("image/png");
          resolve(dataURL.replace(/^data:image\/(png|jpg);base64,/, ""));
        });
      });
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  setBtnDisabled(id) {
    if (document.getElementById(id)) {
      try {
        document.getElementById(id).setAttribute("disabled", "true");
      } catch (error) {
      }
    }
  }

  setBtnEnable(id) {
    if (document.getElementById(id)) {
      try {
        document.getElementById(id).removeAttribute("disabled");
      } catch (error) {
      }
    }
  }

  //  复制链接
  copyUrl(str) {
    this.gloadService.copyString(str);
  }
}
